package cn.edu.hzvtc.controller;

import cn.edu.hzvtc.pojo.*;
import cn.edu.hzvtc.service.msgService;
import cn.edu.hzvtc.service.unitService;
import cn.edu.hzvtc.service.userService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/unit")

public class UnitController {
    @Autowired
    private unitService unitService;
    @Autowired
    private userService userService;
    @Autowired
    private msgService msgService;


    @RequestMapping(value = "/unitTypes", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getUnitTypes(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        List<UnitType> unitTypes = unitService.getUnitTypesByAreaId(user.getUserAreaId());

        return ReturnMsg.success().add("unitTypes", unitTypes);
    }

    //删除
    @RequestMapping(value = "/unitType/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteUnitType(@PathVariable("id") Integer id) {

        if (unitService.deleteUnitType(id)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    //添加
    //添加院校管理员信息
    @RequestMapping(value = "/unitType", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg save(@Valid UnitType unitType, BindingResult result, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        unitType.setUnitTypeAreaId(loginUser.getUserAreaId());
        unitType.setUnitTypeDelState(0);
        if (unitService.addUnitType(unitType) != 0) {
            return ReturnMsg.success();
        }

        return ReturnMsg.fail();
    }

    @RequestMapping(value = "/unitType", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getAreaAdmin(@RequestParam(value = "id") Integer id) {
        UnitType unitType = unitService.getUnitType(id);
        return ReturnMsg.success().add("unitType", unitType);
    }

    @RequestMapping(value = "/unitType/{unitTypeId}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg update(@PathVariable("unitTypeId") Integer unitTypeId, @Valid UnitType unitType, BindingResult result) {
        unitType.setId(unitTypeId);
        unitService.updateUnitType(unitType);
        return ReturnMsg.success();
    }

    @RequestMapping("/units")
    @ResponseBody
    public ReturnMsg getUnits(@RequestParam(value = "unitTypeId", defaultValue = "0") Integer unitTypeId,
                              @RequestParam(value = "unitName", defaultValue = "") String unitName,
                              @RequestParam(value = "pn", defaultValue = "1") Integer pn,
                              HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (pn == -1) {//查询单位类型
            List<Unit> units = unitService.getUnits(unitTypeId, unitName, user.getUserAreaId());
            return ReturnMsg.success().add("units", units);
        } else {//分页查询
            //引入PageHelper分页插件
            //在查询之前只需要传入页码以及每页的大小
            PageHelper.startPage(pn, 5);
            //startPage方法紧跟第一个select查询就是一个分页查询
            List<Unit> units = unitService.getUnits(unitTypeId, unitName, user.getUserAreaId());
            //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
            PageInfo pageInfo = new PageInfo(units, 5);

            return ReturnMsg.success().add("pageInfo", pageInfo);
        }
    }

    @RequestMapping(value = "/unit/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteUnit(@PathVariable("ids") String ids) {

        if (unitService.deleteUnit(ids)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    @RequestMapping(value = "/unit", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg save(@Valid Unit unit, BindingResult result) {
        unit.setUnitDelState(0);
        if (unitService.addUnit(unit) != 0) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    @RequestMapping(value = "/unit", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getUnit(@RequestParam(value = "id") Integer id) {

        Unit unit = unitService.getUnit(id);

        return ReturnMsg.success().add("unit", unit);
    }

    @RequestMapping(value = "/unit/{unitId}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg update(@PathVariable("unitId") Integer unitId, @Valid Unit unit,
                            BindingResult result) {

        //修改操作
        unit.setId(unitId);
        unitService.updateUnit(unit);

        return ReturnMsg.success();
    }

    @RequestMapping(value = "/fileImport")
    @ResponseBody
    public ReturnMsg fileImport(@RequestParam("unitFile") MultipartFile articleFile,
                                HttpSession session) throws Exception {
        String originalFilename = articleFile.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        String[] filename = new String[0];
        if (originalFilename != null) {
            filename = originalFilename.split("\\.");
        }
        if (!filename[filename.length - 1].equals("csv")) {
            return ReturnMsg.fail().add("msg", "文件类型不正确！");
        }
        File file = new File(session.getServletContext().getRealPath("/upload/") + originalFilename);
        try {
            articleFile.transferTo(file);
            List<Unit> units = new ArrayList<Unit>();

            DataInputStream in = new DataInputStream(new FileInputStream(file));
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                String[] str = line.split(",");
                Unit unit = new Unit();
                unit.setUnitName(str[0]);
                unit.setUnitTypeId(Integer.parseInt(str[1]));
                unit.setUnitSortNum(Integer.parseInt(str[2]));
                unit.setUnitDelState(Integer.parseInt(str[3]));
                units.add(unit);
            }
            if (in != null) {
                in.close();
            }
            if (br != null) {
                br.close();
            }
            if (unitService.addUnits(units) != 0) {
                return ReturnMsg.success();
            } else {
                return ReturnMsg.fail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMsg.fail();
        }
    }

    @RequestMapping(value = "/unitCount", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getCount(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");

        Long unitCount = unitService.getCount(loginUser.getUserAreaId());
        Long userCount = userService.getCount(loginUser.getUserAreaId());

        List<MsgCount> allCountsResult = msgService.getAllCountsByAreaId(loginUser.getUserAreaId());
        List<MsgCount> doneCountsResult = msgService.getDoneCountsByAreaId(loginUser.getUserAreaId());
        List<Long> allCounts = new ArrayList<>();
        List<Long> doneCounts = new ArrayList<>();
        List<String> labels = new ArrayList<>();

        for (int i = 0; i < allCountsResult.size(); i++) {
            MsgCount allCount = allCountsResult.get(i);
            MsgCount doneCount = null;
            allCounts.add(allCount.getCount());

            if (i < doneCountsResult.size()) {
                doneCount = doneCountsResult.get(i);
            }


            if (doneCount == null) {
                doneCounts.add(0L);
                doneCountsResult.add(i, null);
            } else {
                doneCounts.add(doneCount.getCount());
            }

            labels.add(allCount.getYear() + "—" + allCount.getMonth());
        }

        return ReturnMsg.success()
                .add("unitCount", unitCount)
                .add("userCount", userCount)
                .add("allCounts", allCounts)
                .add("doneCounts", doneCounts)
                .add("labels", labels);
    }

}

